package cn.xspace.module.other.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.xspace.android.xafcommon.base.BaseAct;
import com.xspace.android.xafcommon.imgload.core.DisplayImageOptions;
import com.xspace.android.xafcommon.util.Constants;
import cn.xspace.library.util.Tools;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.xspace.module.other.bean.Menu_ListData;
import cn.xspace.module.other.bean.Menu_ListItem;
import cn.xspace.module.other.bean.Menu_ListItem2;
import cn.xspace.module.other.http.HttpWorkNet;
import cn.xspace.module.other.util.RProxy;
import com.xspace.android.xafcommon.util.StringToolkit;

public class SubscriptionManageActivity extends BaseAct implements
		OnClickListener {
	private ProgressDialog dialog;
	private List<Menu_ListData> listdata;
	private DisplayImageOptions options;
	private boolean isFinish = false;
	private ExpandableListView listView;

	private int level = 0;
	private int post1 = 0;
	private int post2 = 0;
	private int checkState = 0;
	private BaseAdapter tempAdapter;
	private Context mContext;
	private TextView tv_title;

	@Override
	public void onClick(View v) {
		if (v.getId()==RProxy.btn_return) {
			Intent it = new Intent();
			it.putExtra("isData", isFinish);
			setResult(Activity.RESULT_OK, it);
			finish();
		}
	};

	private Handler handlerList = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			dialog.cancel();
			listAdapter.notifyDataSetChanged();
			switch (msg.arg1) {
			case -1: {
				Toast.makeText(getBaseContext(), "发生未知错误，请尝试退出重试",
						Toast.LENGTH_SHORT).show();
			}
				break;
			case 0: {
			}
				break;
			default:
				break;
			}
		}
	};

	private Handler handlerData = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			dialog.cancel();
			switch (msg.arg1) {
			case -1: {
				Toast.makeText(getBaseContext(), "发生未知错误，请尝试退出重试",
						Toast.LENGTH_SHORT).show();
			}
				break;
			case 0: {
				isFinish = true;
				Constants.isPhonegapMainsNeedRefresh=true;
				Toast.makeText(getBaseContext(), "操作成功", Toast.LENGTH_SHORT)
						.show();
				 listdata.clear();
				 queryData();
				//manageCheckState();
			}
				break;
			default:
				break;
			}
		}
	};

	private void initData() {
		listdata = new ArrayList<Menu_ListData>();
		options = new DisplayImageOptions.Builder().cacheInMemory(true)
				.cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();
		queryData();
	}

	private void initView() {
		listView = (ExpandableListView) findViewById(RProxy.dingyue_listview);
		listView.setGroupIndicator(null);
		listView.setAdapter(listAdapter);
	}

	private BaseExpandableListAdapter listAdapter = new BaseExpandableListAdapter() {

	
		@Override
		public int getGroupCount() {
			// TODO Auto-generated method stub
			return listdata.size();
		}

		@Override
		public int getChildrenCount(int groupPosition) {

			int isItem = listdata.get(groupPosition).getIsGrandsonNode();
			switch (isItem) {
			case 0:
				return 0;
			case 1:
				return 1;
			default:
				return listdata.get(groupPosition).getItem().size();
			}
		}

		@Override
		public Object getGroup(int groupPosition) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getGroupId(int groupPosition) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public boolean hasStableIds() {
			// TODO Auto-generated method stub
			return false;
		}

		class ViewHolderDir {
			ImageView img;
			TextView title;
			CheckBox box;
			ImageView next;
			TextView num;
			View layout;
		}

		class ViewHolderDirChild {
			View high;
			ImageView img;
			View layout;
			GridView gv;
			TextView title;
			CheckBox box;
		}

		@Override
		public View getGroupView(final int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolderDir holder;
			if (convertView == null) {
				holder = new ViewHolderDir();
				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(RProxy.subscriptionmanage_p, parent, false);

				holder.img = (ImageView) convertView
						.findViewById(RProxy.dingyue_wx_img);

				holder.title = (TextView) convertView
						.findViewById(RProxy.dingyue_wx_text);
				holder.box = (CheckBox) convertView
						.findViewById(RProxy.dingyue_wx_cb);
				holder.next = (ImageView) convertView
						.findViewById(RProxy.dingyue_wx_next);
				holder.num = (TextView) convertView
						.findViewById(RProxy.dingyue_wx_num);
				holder.layout = convertView.findViewById(RProxy.dingyue_wx_dy);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolderDir) convertView.getTag();
			}
			final Menu_ListData temp = listdata.get(groupPosition);

			int itemSize = temp.getItem().size();
			if (itemSize == 0) {
				holder.layout.setVisibility(View.GONE);
				// holder.box.setVisibility(View.GONE);
				holder.next.setVisibility(View.GONE);
			} else {
				holder.layout.setVisibility(View.VISIBLE);
				holder.box.setVisibility(View.VISIBLE);
				holder.next.setVisibility(View.VISIBLE);
			}

			if (isExpanded) {
				holder.next.setImageResource(RProxy.ic_dy_icon1);
			} else {
				holder.next.setImageResource(RProxy.ic_dy_icon2);
			}
			if (temp.getIsSubscribed() == 1) {
				holder.box.setChecked(true);
				holder.title.setTextColor(Color.parseColor("#03a87f"));
			} else {
				holder.box.setChecked(false);
				holder.title.setTextColor(Color.parseColor("#666666"));
			}
			holder.box.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (temp.getIsSubscribed() == 1) {
						sendData(temp.getId(), temp.getIsEndCategory(),
								temp.getType(), "0");
						showCheckState(groupPosition, 0, 1, 0, null);
					} else {
						sendData(temp.getId(), temp.getIsEndCategory(),
								temp.getType(), "1");
						showCheckState(groupPosition, 0, 1, 1, null);
					}
				}
			});

			if (temp.getIcon().equals("6")) {
				holder.img.setImageResource(RProxy.ic_dingyue_wx_normal);
			} else {
				holder.img.setImageResource(RProxy.ic_dingyue_dfnx_normal);
			}

			holder.title.setText(temp.getName());
			holder.num.setText(temp.getNumber() + "");

			 if (temp.getCheckbox() == 1) {
			 holder.box.setVisibility(View.VISIBLE);
			 } else {
			 holder.box.setVisibility(View.GONE);
			 }
			return convertView;
		}

		@Override
		public View getChildView(final int groupPosition,
				final int childPosition, boolean isLastChild, View convertView,
				ViewGroup parent) {
			// TODO Auto-generated method stub
			final ViewHolderDirChild holder;
			if (convertView == null) {
				holder = new ViewHolderDirChild();
				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(RProxy.subscriptionmanage_c, parent, false);
				holder.gv = (GridView) convertView
						.findViewById(RProxy.dingyue_item_gv);
				holder.layout = convertView
						.findViewById(RProxy.dingyue_item_layout);
				holder.title = (TextView) convertView
						.findViewById(RProxy.dingyue_item_text);
				holder.box = (CheckBox) convertView
						.findViewById(RProxy.dingyue_item_cb);
				holder.high = convertView
						.findViewById(RProxy.dingyue_item_high);
				holder.img = (ImageView) convertView
						.findViewById(RProxy.dingyue_item_img);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolderDirChild) convertView.getTag();
			}
			final Menu_ListData PlistData = listdata.get(groupPosition);

			List<Menu_ListItem> list_data = PlistData.getItem();

			int isItem = PlistData.getIsGrandsonNode();
			if (isItem == 1) {
				int columnsCount=3;
				if(list_data.size()>0&&list_data.get(0).getName().length()>4){
					columnsCount=2;
				}
				holder.layout.setVisibility(View.GONE);

				DY1_GridViewAdapter dy1GVadapter = new DY1_GridViewAdapter(
						getBaseContext(), list_data, groupPosition);
				holder.gv.setVisibility(View.VISIBLE);
				holder.gv.setNumColumns(columnsCount);
				holder.gv.setAdapter(dy1GVadapter);
				holder.high.setVisibility(View.VISIBLE);

				setListViewHeightBasedOnChildren(dy1GVadapter, list_data,
						holder.gv);

			} else {
				final Menu_ListItem list_data_item = list_data
						.get(childPosition);
				holder.layout.setVisibility(View.VISIBLE);
				holder.title.setText(list_data_item.getName());
				List<Menu_ListItem2> list_data_item_item = list_data_item
						.getItem();

				final DY2_GridViewAdapter dy1GVadapter = new DY2_GridViewAdapter(
						getBaseContext(), list_data_item_item, groupPosition,
						childPosition);
				holder.gv.setNumColumns(3);
				holder.gv.setAdapter(dy1GVadapter);
				if (list_data.size() - 1 == childPosition) {
					holder.high.setVisibility(View.VISIBLE);
				} else {
					holder.high.setVisibility(View.GONE);
				}
				if (list_data_item.isExpanded()) {
					holder.gv.setVisibility(View.VISIBLE);
				} else {
					holder.gv.setVisibility(View.GONE);
				}
				if (list_data_item.getIsSubscribed() == 1) {
					holder.box.setChecked(true);
					holder.title.setTextColor(Color.parseColor("#03a87f"));
				} else {
					holder.box.setChecked(false);
					holder.title.setTextColor(Color.parseColor("#666666"));
				}
				if(list_data_item.getCheckbox()==1){
					holder.box.setVisibility(View.VISIBLE);
				}
				else{
					holder.box.setVisibility(View.GONE);
				}
				holder.layout.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (list_data_item.isExpanded()) {
							holder.gv.setVisibility(View.GONE);
							holder.img
									.setImageResource(RProxy.ic_x581_img_normal);
							list_data_item.setExpanded(false);
						} else {
							holder.gv.setVisibility(View.VISIBLE);
							holder.img.setImageResource(RProxy.ic_x581_img_p);
							list_data_item.setExpanded(true);
						}
					}
				});
				holder.box.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (list_data_item.getIsSubscribed() == 1) {
							sendData(list_data_item.getId(),
									list_data_item.getIsEndCategory(),
									list_data_item.getType(), "0");
							showCheckState(groupPosition, childPosition, 2, 0,
									dy1GVadapter);
						} else {
							sendData(list_data_item.getId(),
									list_data_item.getIsEndCategory(),
									list_data_item.getType(), "1");
							showCheckState(groupPosition, childPosition, 2, 1,
									dy1GVadapter);
						}
					}
				});
				setListViewHeightBasedOnChildren(dy1GVadapter,
						list_data_item_item, holder.gv);
			}

			return convertView;
		}

		// public void setFinishView() {
		// for (int i = 0, j = listdata.size(); i < j; i++) {
		// Menu_ListData tempData = listdata.get(i);
		// List<Menu_ListItem> listItemData = tempData.getItem();
		// for (int x = 0, y = listItemData.size(); x < y; x++) {
		//
		// }
		// }
		// }

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return false;
		}
	};

	//@SuppressLint("NewApi")
	public void setListViewHeightBasedOnChildren(
			DY2_GridViewAdapter itemAdapter,
			List<Menu_ListItem2> list_data_item_item, GridView gridview) {
		int itemListSize = list_data_item_item.size();
		int numRom = 0;
		int numRor = 0;
		for (int i = 0; i < itemListSize; i++) {
			Menu_ListItem2 tempItem = list_data_item_item.get(i);
			if (tempItem.getName().length() > numRom)
				numRom = tempItem.getName().length();
		}
		if (numRom <= 3) {
			numRor = 4;
		} else if (numRor <= 5) {
			numRor = 3;
		} else if (numRor <= 7) {
			numRor = 2;
		} else {
			numRor = 1;
		}

		int gridviewHB = 0;
		if (itemListSize % numRor == 0) {
			gridviewHB = list_data_item_item.size() / numRor;
		} else {
			gridviewHB = list_data_item_item.size() / numRor + 1;
		}
		LinearLayout.LayoutParams gridViewLP = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);

		DY2_GridViewAdapter itemAdapter2 = (DY2_GridViewAdapter) gridview
				.getAdapter();
		if (itemAdapter2 == null) {
			return;
		}

		View listItem = itemAdapter2.getView(0, null, gridview);
		listItem.measure(0, 0);
		int totalHeight = listItem.getMeasuredHeight();
		gridview.setNumColumns(numRor);
		gridViewLP.setMargins(40, 0, 0, 20);

			gridViewLP.height = gridviewHB
					* (totalHeight + StringToolkit.dip2px(
							getApplicationContext(), 5))
					+ StringToolkit.dip2px(getApplicationContext(), 21);
		gridview.setLayoutParams(gridViewLP);
	}

	//@SuppressLint("NewApi")
	public void setListViewHeightBasedOnChildren(
			DY1_GridViewAdapter itemAdapter,
			List<Menu_ListItem> list_data_item_item, GridView gridview) {
		int itemListSize = list_data_item_item.size();
		int numRom = 0;
		int numRor = 0;
		for (int i = 0; i < itemListSize; i++) {
			Menu_ListItem tempItem = list_data_item_item.get(i);
			if (tempItem.getName().length() > numRom)
				numRom = tempItem.getName().length();
		}
		if (numRom <= 3) {
			numRor = 4;
		} else if (numRor <= 5) {
			numRor = 3;
		} else if (numRor <= 7) {
			numRor = 2;
		} else {
			numRor = 1;
		}

		int gridviewHB = 0;
		if (itemListSize % numRor == 0) {
			gridviewHB = list_data_item_item.size() / numRor;
		} else {
			gridviewHB = list_data_item_item.size() / numRor + 1;
		}
		LinearLayout.LayoutParams gridViewLP = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);

		DY1_GridViewAdapter itemAdapter2 = (DY1_GridViewAdapter) gridview
				.getAdapter();
		if (itemAdapter2 == null) {
			return;
		}

		View listItem = itemAdapter2.getView(0, null, gridview);
		listItem.measure(0, 0);
		int totalHeight = listItem.getMeasuredHeight();
		gridview.setNumColumns(numRor);
		gridViewLP.setMargins(40, 0, 0, 20);

			gridViewLP.height = gridviewHB
					* (totalHeight + StringToolkit.dip2px(
							getApplicationContext(), 5))
					+ StringToolkit.dip2px(getApplicationContext(), 21);
		
		gridview.setLayoutParams(gridViewLP);
	}

	private void showCheckState(int post1, int post2, int level,
			int checkState, BaseAdapter tempAdapter) {
		this.level = level;
		this.post1 = post1;
		this.post2 = post2;
		this.checkState = checkState;
		this.tempAdapter = tempAdapter;
	}

	private void manageCheckState() {
		switch (level) {
		case 1: {
			Menu_ListData itemData = listdata.get(post1);
			List<Menu_ListItem> itemList = itemData.getItem();
			for (int i = 0, j = itemList.size(); i < j; i++) {
				Menu_ListItem tempData2 = itemList.get(i);
				List<Menu_ListItem2> itemList2 = tempData2.getItem();

				for (int x = 0, y = itemList2.size(); x < y; x++) {
					Menu_ListItem2 item = itemList2.get(x);
					if (checkState == 1) {
						item.setIsSubscribed(1);
					} else {
						item.setIsSubscribed(0);
					}
				}
				if (checkState == 1) {
					tempData2.setIsSubscribed(1);
				} else {
					tempData2.setIsSubscribed(0);
				}
			}
			if (checkState == 1) {
				itemData.setIsSubscribed(1);
			} else {
				itemData.setIsSubscribed(0);
			}
			mNotifyDataSetChanged();
		}
			break;
		case 2: {
			DY2_GridViewAdapter apater = (DY2_GridViewAdapter) tempAdapter;
			List<Menu_ListItem2> itemList = apater.data;
			for (int i = 0, j = itemList.size(); i < j; i++) {
				Menu_ListItem2 item = itemList.get(i);
				if (checkState == 1) {
					item.setIsSubscribed(1);
				} else {
					item.setIsSubscribed(0);
				}
			}
			if (checkState == 1) {
				listdata.get(post1).getItem().get(post2).setIsSubscribed(1);
			} else {
				listdata.get(post1).getItem().get(post2).setIsSubscribed(0);
			}
			List<Menu_ListItem> itemData1 = listdata.get(apater.groupPosition)
					.getItem();
			for (int i = 0, j = itemData1.size(); i < j; i++) {
				Menu_ListItem f_item = itemData1.get(i);
				if (checkState == 0) {
					if (f_item.getIsSubscribed() == checkState) {
						listdata.get(apater.groupPosition).setIsSubscribed(
								checkState);
						mNotifyDataSetChanged();
						return;
					}
				} else {
					if (f_item.getIsSubscribed() != checkState) {
						mNotifyDataSetChanged();
						return;
					}
				}
			}
			listdata.get(apater.groupPosition).setIsSubscribed(checkState);
		mNotifyDataSetChanged();
		}
			break;
		case 3: {
			DY2_GridViewAdapter apater = (DY2_GridViewAdapter) tempAdapter;
			Menu_ListItem2 item = apater.data.get(post1);
			if (checkState == 1) {
				item.setIsSubscribed(1);
			} else {
				item.setIsSubscribed(0);
			}
			List<Menu_ListItem> itemData1 = listdata.get(apater.groupPosition)
					.getItem();
			List<Menu_ListItem2> itemData2 = itemData1
					.get(apater.childPosition).getItem();
			for (int i = 0, j = itemData2.size(); i < j; i++) {
				Menu_ListItem2 f_item = itemData2.get(i);
				if (checkState == 0) {
					if (f_item.getIsSubscribed() == checkState) {
						itemData1.get(apater.childPosition).setIsSubscribed(
								checkState);
						listdata.get(apater.groupPosition).setIsSubscribed(
								checkState);
						mNotifyDataSetChanged();
						return;
					}
				} else {
					if (f_item.getIsSubscribed() != checkState) {
						mNotifyDataSetChanged();
						return;
					}
				}
			}
			itemData1.get(apater.childPosition).setIsSubscribed(checkState);
			for (int i = 0, j = itemData1.size(); i < j; i++) {
				Menu_ListItem f_item = itemData1.get(i);
				if (f_item.getIsSubscribed() != checkState) {
					mNotifyDataSetChanged();
					return;
				}
			}
			listdata.get(apater.groupPosition).setIsSubscribed(checkState);
			mNotifyDataSetChanged();
		}
			break;
		case 4: {
			DY1_GridViewAdapter apater = (DY1_GridViewAdapter) tempAdapter;
			Menu_ListItem item = apater.data.get(post1);
			if (checkState == 1) {
				item.setIsSubscribed(1);
			} else {
				item.setIsSubscribed(0);
			}
			List<Menu_ListItem> itemData1 = listdata.get(apater.groupPosition)
					.getItem();
			for (int i = 0, j = itemData1.size(); i < j; i++) {
				Menu_ListItem f_item = itemData1.get(i);
				if (checkState == 0) {
					if (f_item.getIsSubscribed() == checkState) {
						listdata.get(apater.groupPosition).setIsSubscribed(
								checkState);
						mNotifyDataSetChanged();
						return;
					}
				} else {
					if (f_item.getIsSubscribed() != checkState) {
						mNotifyDataSetChanged();
						return;
					}
				}
			}
			listdata.get(apater.groupPosition).setIsSubscribed(checkState);
			mNotifyDataSetChanged();
		}
			break;
		default:
			break;
		}
	}

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(RProxy.activity_subscriptionmanage2);
		mContext = this;
		initTops();
		initData();
		initView();

	}

	private void initTops() {
		setHomeTitleBarBg(findViewById(RProxy.r_item));
		tv_title = (TextView) findViewById(RProxy.topbar_title);
		tv_title.setText("订阅管理");
		findViewById(RProxy.btn_return).setOnClickListener(this);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void queryData() {
		dialog = ProgressDialog.show(SubscriptionManageActivity.this, "",
				"系统正在处理...", true);
		JSONObject js = new JSONObject();
		try {
			String user_id = Tools.getCurrentAccountInfo(this).uuid;
			user_id = user_id.split("@")[0];
			js.put("user_id", user_id);
			js.put("platform", "1");
		} catch (Exception e) {
			e.printStackTrace();
		}
		new HttpWorkNet(this, Constants.QueryAllSubscribeCategory,
				new ListAsync()).sendData(js);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void sendData(String id, int isEndCategory, int platform,
			String subscribe) {
		dialog = ProgressDialog.show(SubscriptionManageActivity.this, "",
				"系统正在处理...", true);
		JSONObject js = new JSONObject();
		try {
			String user_id = Tools.getCurrentAccountInfo(this).uuid;
			user_id = user_id.split("@")[0];
			js.put("user_id", user_id);
			js.put("id", id);
			// js.put("type", 1);
			js.put("platform", "1");
			// js.put("isEndCategory", isEndCategory);
			js.put("subscribe", subscribe);
		} catch (Exception e) {
			e.printStackTrace();
		}
		new HttpWorkNet(this, Constants.SubCateogry, new queryAsync())
				.sendData(js);
	}

	private class ListAsync extends AsyncTask<Object, Object, Integer> {

		protected Integer doInBackground(Object... params) {

			try {
				JSONObject js = (JSONObject) params[1];
				int num = js.getInt("code");
				if (num == 0) {
					JSONArray jsArr = js.getJSONArray("categoryList");
					for (int i = 0, j = jsArr.length(); i < j; i++) {
						JSONObject jsItem = jsArr.getJSONObject(i);
						Menu_ListData p_ListData = new Menu_ListData();
						// p_ListData.setType(jsItem.getInt("type"));
						p_ListData.setIsGrandsonNode(jsItem
								.getInt("isGrandsonNode"));
						p_ListData.setId(jsItem.getString("c_id"));

						// p_ListData.setIcon(jsItem.optString("logo"));
						p_ListData.setIcon(jsItem.optString("imag_flag"));

						p_ListData.setName(jsItem.optString("name"));
						p_ListData.setNumber(jsItem.optInt("num"));
						p_ListData.setSysn(jsItem.optBoolean("isSysn"));
						p_ListData.setIsSubscribed(jsItem
								.optInt("isSubscribed"));
						p_ListData.setIsEndCategory(jsItem
								.optInt("isEndCategory"));
						p_ListData.setNoSubscribe(jsItem.optInt("noSubscribe"));
						p_ListData.setCategory_code(jsItem
								.optString("category_code"));
						p_ListData.setCheckbox(jsItem.optInt("checkbox"));

						JSONArray jsArr2 = jsItem.optJSONArray("childList");
						if (jsArr2 != null) {
							List<Menu_ListItem> itemList = new ArrayList<Menu_ListItem>();
							for (int x = 0, y = jsArr2.length(); x < y; x++) {
								JSONObject jsItem2 = jsArr2.getJSONObject(x);
								Menu_ListItem c_item = new Menu_ListItem();
								// c_item.setType(jsItem2.getInt("type"));
								// c_item.setIsGrandsonNode(jsItem2.getInt("isGrandsonNode"));
								c_item.setId(jsItem2.getString("c_id"));
								c_item.setLogo(jsItem2.optString("logo"));
								c_item.setName(jsItem2.optString("name"));
								c_item.setNum(jsItem2.optInt("num"));
								c_item.setCategory_code(jsItem2
										.optString("category_code"));
								c_item.setSysn(jsItem2.optBoolean("isSysn"));
								c_item.setIsSubscribed(jsItem2
										.optInt("isSubscribed"));
								c_item.setIsEndCategory(jsItem2
										.optInt("isEndCategory"));
								c_item.setNoSubscribe(jsItem2
										.optInt("noSubscribe"));
								c_item.setCheckbox(jsItem2.optInt("checkbox"));
								// 0 有节点
								JSONArray jsArr3 = jsItem2
										.optJSONArray("childList");
								if (jsArr3 != null) {
									List<Menu_ListItem2> itemList2 = new ArrayList<Menu_ListItem2>();
									for (int a = 0, b = jsArr3.length(); a < b; a++) {
										JSONObject jsItem3 = jsArr3
												.getJSONObject(a);
										Menu_ListItem2 c_item2 = new Menu_ListItem2();
										// c_item2.setType(jsItem3.getInt("type"));
										// c_item2.setIsGrandsonNode(jsItem3.getInt("isGrandsonNode"));
										c_item2.setId(jsItem3.getString("c_id"));
										c_item2.setLogo(jsItem3
												.optString("logo"));
										c_item2.setName(jsItem3
												.optString("name"));
										c_item2.setNum(jsItem3.optInt("num"));
										c_item2.setCategory_code(jsItem3
												.optString("category_code"));
										c_item2.setSysn(jsItem3
												.optBoolean("isSysn"));
										c_item2.setIsSubscribed(jsItem3
												.optInt("isSubscribed"));
										c_item2.setIsEndCategory(jsItem3
												.optInt("isEndCategory"));
										c_item2.setNoSubscribe(jsItem3
												.optInt("noSubscribe"));
										itemList2.add(c_item2);
									}
									c_item.setItem(itemList2);
								} else {
									List<Menu_ListItem2> itemList2 = new ArrayList<Menu_ListItem2>();
									c_item.setItem(itemList2);
								}
								itemList.add(c_item);
							}
							p_ListData.setItem(itemList);
						} else {
							List<Menu_ListItem> itemList = new ArrayList<Menu_ListItem>();
							p_ListData.setItem(itemList);
						}
						listdata.add(p_ListData);
					}
					return 0;
				}
				return num;
			} catch (Exception e) {
				e.printStackTrace();
				return -1;
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			Message ms = new Message();
			ms.arg1 = result;
			handlerList.sendMessage(ms);
		}

	}

	private class queryAsync extends AsyncTask<Object, Object, Integer> {

		protected Integer doInBackground(Object... params) {

			try {
				JSONObject js = (JSONObject) params[1];
				return js.getInt("code");
			} catch (Exception e) {
				e.printStackTrace();
				return -1;
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			Message ms = new Message();
			ms.arg1 = result;
			handlerData.sendMessage(ms);
		}

	}

	class DY1_GridViewAdapter extends BaseAdapter {
		public List<Menu_ListItem> data;
		private Context context;
		public int groupPosition = 0;

		public DY1_GridViewAdapter(Context context, List<Menu_ListItem> data,
				int groupPosition) {
			this.data = data;
			this.context = context;
			this.groupPosition = groupPosition;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return data.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		class ViewHolder {
			TextView title;
			CheckBox box;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(context).inflate(
						RProxy.subscriptionmanage_c1, parent, false);
				holder.title = (TextView) convertView
						.findViewById(RProxy.dingyue_item_gv_text);
				holder.box = (CheckBox) convertView
						.findViewById(RProxy.dingyue_item_gv_text_cb);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (data == null || data.isEmpty()) {
				return convertView;
			}
			final Menu_ListItem item = data.get(position);
			holder.title.setText(item.getName());
			if (item.getIsSubscribed() == 1) {
				holder.box.setChecked(true);
			} else {
				holder.box.setChecked(false);
			}
			holder.box.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (item.getIsSubscribed() == 1) {
						sendData(item.getId(), item.getIsEndCategory(),
								item.getType(), "0");
						showCheckState(position, 0, 4, 0,
								DY1_GridViewAdapter.this);
					} else {
						sendData(item.getId(), item.getIsEndCategory(),
								item.getType(), "1");
						showCheckState(position, 0, 4, 1,
								DY1_GridViewAdapter.this);
					}
				}
			});
			return convertView;
		}
	}

	class DY2_GridViewAdapter extends BaseAdapter {
		public List<Menu_ListItem2> data;
		private Context context;
		public int childPosition = 0;
		public int groupPosition = 0;

		public DY2_GridViewAdapter(Context context, List<Menu_ListItem2> data,
				int groupPosition, int childPosition) {
			this.data = data;
			this.context = context;
			this.groupPosition = groupPosition;
			this.childPosition = childPosition;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return data.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		class ViewHolder {
			TextView title;
			CheckBox box;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(context).inflate(
						RProxy.subscriptionmanage_c1, parent, false);
				holder.title = (TextView) convertView
						.findViewById(RProxy.dingyue_item_gv_text);
				holder.box = (CheckBox) convertView
						.findViewById(RProxy.dingyue_item_gv_text_cb);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (data == null || data.isEmpty()) {
				return convertView;
			}

			final Menu_ListItem2 item = data.get(position);
			holder.title.setText(item.getName());
			if (item.getIsSubscribed() == 1) {
				holder.box.setChecked(true);
			} else {
				holder.box.setChecked(false);
			}
			holder.box.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (item.getIsSubscribed() == 1) {
						sendData(item.getId(), item.getIsEndCategory(),
								item.getType(), "0");
						showCheckState(position, 0, 3, 0,
								DY2_GridViewAdapter.this);
					} else {
						sendData(item.getId(), item.getIsEndCategory(),
								item.getType(), "1");
						showCheckState(position, 0, 3, 1,
								DY2_GridViewAdapter.this);
					}
				}
			});
			return convertView;
		}

	}

	/**
	 * 计算订阅个数
	 * @return
	 */
	private int[] countSubNum() {
		int[] list = new int[listdata.size()];

		for (int i = 0; i < listdata.size(); i++) {
			int count = 0;
			Menu_ListData md = listdata.get(i);
			List<Menu_ListItem> tlist = md.getItem();
			
			if (tlist != null && tlist.size() > 0) {
				for (int j = 0; j < tlist.size(); j++) {
					Menu_ListItem menu1 = tlist.get(j);
					List<Menu_ListItem2> tlist1 = menu1.getItem();
					if (tlist1 == null || tlist1.size() == 0) {
						count += menu1.getIsSubscribed();
						continue;
					}
					int temp_c = 0;
					for (int k = 0; k < tlist1.size(); k++) {
						Menu_ListItem2 menu2 = tlist1.get(k);
						temp_c += menu2.getIsSubscribed();
					}
					count += temp_c;
				}
				
			}
			//Log.i("subscribe", "countSubNum count:" + count);
			list[i]=count;
		}
		
		return list;
	}
	/**
	 * 订阅个数重新赋值
	 * @param list
	 */
	public void setSubCount(int[] list) {
		if(list==null || list.length!=listdata.size()) return;
		for (int i = 0; i < listdata.size(); i++) {
			Menu_ListData data=listdata.get(i);
			data.setNumber(list[i]);
		}
	}
	
	private void mNotifyDataSetChanged() {
		setSubCount(countSubNum());
		listAdapter.notifyDataSetChanged();
	}
}
